#include <new>

#include "library2.h"
#include "system.hpp"

#define RUN_SYSTEM_METHOD(command) do { \
	if (NULL == DS) { \
		return INVALID_INPUT; \
	} \
	try { \
		command; \
	} \
	catch (std::bad_alloc&) { \
		return ALLOCATION_ERROR; \
	} \
	catch (FailureException&) {	\
		return FAILURE; \
	} \
	return SUCCESS; \
} while (0)

void* Init(int n) {
	System* DS = NULL;
	try {
		DS = new System(n);
	}
	catch (std::bad_alloc) {
		return NULL;
	}
	return (void*)DS;
}

StatusType AddGame(void *DS, int gameID, int companyID, int gameRate) {
	RUN_SYSTEM_METHOD(((System*)DS)->addGame(gameID, companyID, gameRate));
}

StatusType RemoveGame(void *DS, int gameID) {
	RUN_SYSTEM_METHOD(((System*)DS)->removeGame(gameID));
}

StatusType GetGameCompany(void *DS, int gameID, int *ret) {
	RUN_SYSTEM_METHOD(*ret = ((System*)DS)->getGameCompany(gameID));
}

StatusType MergeCompanies(void *DS, int company1, int company2) {
	RUN_SYSTEM_METHOD(((System*)DS)->mergeCompanies(company1, company2));
}

StatusType GetMinIDGameOfRate(void *DS, int minRate, int *ret) {
	RUN_SYSTEM_METHOD(*ret = ((System*)DS)->getMinIdGameOfRate(minRate));
}

void Quit(void** DS) {
	if ((NULL == DS) || (NULL == *DS)) {
		return;
	}
	delete (System*)*DS;
	*DS = NULL;
}